﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.IO;
namespace FinosLibrary {
    [DataContract]
    public class Package {
        [DataMember(Order = 0)]
        public string head { get; set; }
        [DataMember(Order = 1)]
        public string body { get; set; }
        public byte[] byteBody;
        public Package() { }
        public Package(string h) { head = h; }
        public Package(string h, object b) {
            head = h;
            body = b is string ? b as string : b.ToJson();
        }
        public T getBody<T>() {
            if (body != null) {
                return body.FromJsonTo<T>();
            } else {
                return default(T);
            }
        }
        public void setBody(object b) {
            body = b.ToJson();
        }
        public byte[] toBytes() {
            byte[] json = byteBody == null ? this.ToJsonBytes() : byteBody;
            byte[] result = new byte[4 + json.Length];
            BitConverter.GetBytes(json.Length).CopyTo(result, 0);
            json.CopyTo(result, 4);
            return result;
        }
        public override string ToString() {
            return "\nhead:" + head + "\nbody:" + body;
        }
    }
}